/* jshint esversion:6 */
import React, {
  Component,
  PropTypes
} from 'react';

import './CheckBox.scss';

import _ from 'lodash';


export default class CheckBox extends Component {
  static CLASS = {
    DEFAULT: 'checkbox'
  };
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <CheckBox.Item {...this.props}/>
    );
  }
}


CheckBox.Group = class extends Component {
  render() {
    const { dataList, defaultCheckedList } = this.props;
    const nodes = dataList.map( (data) => {
      const { name, value, labelText } = data;
      let isChecked = false;
      if (value.indexOf(defaultCheckedList) > -1) {
        isChecked = true;
      }
      return <CheckBox.Item checked={isChecked} {...data} />
    } );
    return (
      <div>
        {nodes}
      </div>
    )
  }
}

CheckBox.Group.PropTypes = {
  dataList: PropTypes.array.isRequired,
  defaultCheckedList: PropTypes.array,
  onValueChange: PropTypes.func
};



CheckBox.Item = class extends Component {
  constructor(props) {
    super(props);
    this._onChange = this._onChange.bind(this);
  }

  _onChange(e) {
    const { value } = e.target;
    const { onValueChange } = this.props;
    if (_.isFunction(onValueChange)) {
      onValueChange(value);
    }
  }

  render() {
    const { name, value, checked, labelText } = this.props;
    return (
      <span>
        <input onChange={this._onChange} type="checkbox" name={name} value={value} defaultChecked={checked} />
        {labelText ? <span>{ labelText }</span> : ''}
      </span>
    );
  }
};

CheckBox.Item.PropTypes = {
  name: PropTypes.string,
  value: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number
  ]).isRequired,
  checked: PropTypes.bool,
  labelText: PropTypes.string
}
